package org.desktop.web.client.custom.widget.grid.timesheet;


import java.util.ArrayList;
import java.util.List;

import org.desktop.web.shared.util.WebService;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.data.client.loader.HttpProxy;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.loader.ListLoadConfig;
import com.sencha.gxt.data.shared.loader.ListLoadResult;
import com.sencha.gxt.data.shared.loader.ListLoader;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.widget.core.client.form.DateField;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.form.TimeField;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.editing.GridEditing;
import com.sencha.gxt.widget.core.client.grid.editing.GridRowEditing;

public class TimesheetGrid implements IsWidget {

	@Override
	public Widget asWidget() {
		
		TimesheetAutoBeanFactory factory = GWT.create(TimesheetAutoBeanFactory.class);
		
		TimesheetDataRecordJsonReader reader = new TimesheetDataRecordJsonReader(factory, TimesheetRecordResult.class);
		
		String url = GWT.getModuleBaseURL()+"exec?service="+WebService.NORMAL_WORKING_TIME;
		
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		HttpProxy<ListLoadConfig> proxy = new HttpProxy<ListLoadConfig>(builder);
		
		final ListLoader<ListLoadConfig, ListLoadResult<Timesheet>> loader = new ListLoader<ListLoadConfig, ListLoadResult<Timesheet>>(proxy,reader);
		loader.useLoadConfig(factory.create(ListLoadConfig.class).as());
		
		TimesheetProperties properties = GWT.create(TimesheetProperties.class);
		
		ListStore<Timesheet> store = new ListStore<Timesheet>(properties.key());

		loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, Timesheet, ListLoadResult<Timesheet>>(store));
		
		ColumnConfig<Timesheet, String> ccStart = new ColumnConfig<Timesheet, String>(properties.start_time(),100,"Ora inizio");
		ColumnConfig<Timesheet, String> ccEnd = new ColumnConfig<Timesheet, String>(properties.end_time(),100,"Ora fine");
		
		List<ColumnConfig<Timesheet, ?>> columns = new ArrayList<ColumnConfig<Timesheet,?>>();
		columns.add(ccStart);
		columns.add((ccEnd));
		
		ColumnModel<Timesheet> cm = new ColumnModel<Timesheet>(columns); 
		
		Grid<Timesheet> grid = new Grid<Timesheet>(store, cm);
		final GridEditing<Timesheet> editing = new GridRowEditing<Timesheet>(grid);
	      editing.addEditor(ccStart, new TextField());
	      editing.addEditor(ccEnd, new TextField());
		loader.load();
		// TODO Auto-generated method stub
		return grid;
	}

}
